/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package transervfx.Dato.DAO;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import transervfx.Dato.Entidad.Gestor;

/**
 *
 * @author oscar
 */
public class GestorDAO implements Dao<Gestor, Long> {

    private static GestorDAO INSTANCE = null;

    /**
     * Crea el Gestor Auxiliar
     */
    protected GestorDAO() {
    }

    /**
     * creador sincronizado para protegerse de posibles problemas multi-hilo
     * otra prueba para evitar instanciación múltiple
     */
    private synchronized static void createInstance() {
        if (INSTANCE == null) {
            INSTANCE = new GestorDAO();
        }
    }

    /**
     * Obtiene la instancia.
     *
     * @return devuelve la instancia del "GestorAuxiliar".
     */
    public static GestorDAO getInstance() {
        if (INSTANCE == null) {
            createInstance();
        }
        return INSTANCE;
    }

    @Override
    public void persist(Gestor entity) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                em.persist(entity);
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    
    @Override
    public void remove(Gestor entity) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                System.out.println("ESTAS POR ELIMIAR");
                entity = em.getReference(Gestor.class, entity.getId());
                em.remove(entity);
                System.out.println("LO ELIMINA");
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    @Override
    public void update(Gestor entity) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {


            em.getTransaction().begin();
            System.out.println("Entra a modificar el Gestor");
            em.merge(entity);

            em.getTransaction().commit();
            System.out.println("Lo modifica al Gestor");

        } finally {
            em.close();
        }
    }

    @Override
    public Gestor findById(Long id) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            return em.getReference(Gestor.class, id);

        } finally {
            em.close();
        }
    }

    @Override
    public List<Gestor> findAll() {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            return em.createNamedQuery("Gestor.findAll").getResultList();

        } finally {
            em.close();
        }
    }

    public Gestor findByCompleto(Gestor gestorSeleccionado) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            gestorSeleccionado = em.find(Gestor.class, gestorSeleccionado.getId());
            gestorSeleccionado.getDomicilio();
            return gestorSeleccionado;

        } finally {
            em.close();
        }
    }

    public List<Gestor> findByNombresAndApellido(String nombres, String apellido) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            Query query = em.createNamedQuery("Gestor.findByNombresAndApellido");
            query.setParameter("nombres", nombres);
            query.setParameter("apellido", apellido);

            return query.getResultList();

        } finally {
            em.close();
        }
    }

    public Gestor findByCuit(Integer cuit) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createNamedQuery("Gestor.findByCuit");
            query.setParameter("cuit", cuit);
            if (query.getResultList().isEmpty()) {
                return null;
            }
            return (Gestor) query.getResultList().get(0);
        } finally {
            em.close();
        }
    }

    public List<Gestor> findByTipoDoc(String tipoDoc) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {

            Query query = em.createNamedQuery("Gestor.findByTipoDoc");
            query.setParameter("tipoDoc", tipoDoc);
            return query.getResultList();

        } finally {
            em.close();
        }
    }

    public Gestor findByNroDoc(Integer nroDoc) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createNamedQuery("Gestor.findByNroDoc");
            query.setParameter("nroDoc", nroDoc);
            if (query.getResultList().isEmpty()) {
                return null;
            }
            return (Gestor) query.getResultList().get(0);
        } finally {
            em.close();
        }
    }

    public Gestor findByTipoDocAndNroDoc(String tipoDoc, Integer nroDoc) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {


            Query query = em.createNamedQuery("Gestor.findByTipoDocAndNroDoc");
            query.setParameter("tipoDoc", tipoDoc);
            query.setParameter("nroDoc", nroDoc);

            List<Gestor> lr = query.getResultList();
            if (lr.size() > 0) {
                return lr.get(0);
            } else {
                return null;
            }


        } finally {
            em.close();
        }
    }

    public Long numeroDeGestoresFiltrados(String apellido, String nombres, String tipoDocumento, Integer numeroDocumento, String condicionIva) {


        String consulta = "SELECT COUNT(p) FROM Gestor p ";

        boolean hayotroParametro = false;

        if (!apellido.equals("") || !nombres.equals("") || !tipoDocumento.equals("") || numeroDocumento != null || !condicionIva.equals("")) {
            consulta = "SELECT COUNT(p) FROM Gestor p WHERE";
            if (!apellido.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }

                consulta = consulta + " p.apellido LIKE " + "'" + apellido + "%'";
                hayotroParametro = true;
            }
            if (!nombres.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }

                consulta = consulta + " p.nombres LIKE " + "'" + nombres + "%'";


            }
            if (!tipoDocumento.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }

                consulta = consulta + " p.tipoDoc LIKE " + "'" + tipoDocumento + "'";

            }
            if (numeroDocumento != null) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }
                consulta = consulta + " p.nroDoc =" + numeroDocumento;

            }
            //pero en la bd creo que habia de los dos
            if (!condicionIva.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }
                consulta = consulta + " p.condicionFrenteIva LIKE " + "'" + condicionIva + "'";
            }


        }


        System.out.println(consulta);
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createQuery(consulta);

            return (Long) query.getSingleResult();

        } finally {
            em.close();
        }
    }

    public List<Gestor> buscarPorFiltroRango(String apellido, String nombres, String tipoDocumento, Integer numeroDocumento, String condicionIva, int ini, int fin) {

        System.out.println("Entra buscarPorFiltroRango");

        String consulta = "SELECT p FROM Gestor p";
        boolean hayotroParametro = false;

        if (!apellido.equals("") || !nombres.equals("") || !tipoDocumento.equals("") || numeroDocumento != null || !condicionIva.equals("")) {
            consulta = "SELECT p FROM Gestor p WHERE";
            if (!apellido.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }

                consulta = consulta + " p.apellido LIKE " + "'" + apellido + "%'";
                hayotroParametro = true;
            }
            if (!nombres.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }

                consulta = consulta + " p.nombres LIKE " + "'" + nombres + "%'";


            }
            if (!tipoDocumento.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }

                consulta = consulta + " p.tipoDoc LIKE " + "'" + tipoDocumento + "'";

            }
            if (numeroDocumento != null) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }
                consulta = consulta + " p.nroDoc =" + numeroDocumento;
            }
            if (!condicionIva.equals("")) {
                if (hayotroParametro) {
                    consulta = consulta + " AND ";
                } else {
                    hayotroParametro = true;
                }
                consulta = consulta + " p.condicionFrenteIva LIKE " + "'" + condicionIva + "'";
            }


        }
        System.out.println(consulta);

        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {
            Query query = em.createQuery(consulta);
            query.setFirstResult(ini);
            query.setMaxResults(fin);

            return (List<Gestor>) query.getResultList();

        } finally {
            em.close();
        }
    }

    public boolean poseeGuia(Gestor r) {
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        try {


            Gestor rAux = em.find(Gestor.class, r.getId());
            System.out.println("TRAE AL GESTOR");
            System.out.println("CANTIDAD DE GUIAS " + rAux.getGuiasTramites().size());
            if (rAux.getGuiasTramites() != null) {
                System.out.println("LA GUIA DE TRAMITE NO ES NULL");
                if (!rAux.getGuiasTramites().isEmpty()) {
                    System.out.println("POSEE GUIAS DE TRAMITE");
                    return true;
                }

            }
            System.out.println("NO POSEE GUIAS DE TRAMITE");
            return false;

        } finally {
            em.close();
        }

    }
}
